<template>
  <div class="hm-cover">
    <!-- 图片按钮 -->
    <div class="btn_img" @click="openDialog" style="cursor: pointer;">
      <img :src="currentImage" />
    </div>
    <!-- 对话框开始 -->
    <el-dialog
    title="上传封面"
    :visible.sync="dialogVisible"
    width="50%">
    <div class="dialog-body-content">
      <el-tabs v-model="activeName">
        <!-- 素材库tab栏 -->
        <el-tab-pane label="素材库" name="image">
            <!-- 头部按钮组 -->
             <div>
                <el-radio-group v-model="collect" @change="btnChange">
                    <el-radio-button :label="false">全部</el-radio-button>
                    <el-radio-button :label="true">收藏</el-radio-button>
                </el-radio-group>
            </div>
            <!-- 中间图片组 -->
            <el-row :gutter="10">
                <el-col :span="6" v-for="item in pictures" :key="item.id">
                    <el-image
                    style="width: 100%; height: 150px"
                    :class="{selected:item.url===selectedImageUrl}"
                    :src="item.url"
                    fit="cover"
                    @click.native="select(item.url)">
                    </el-image>
                </el-col>
            </el-row>
            <!-- 底部分页 -->
            <el-pagination
                background
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-size="per_page"
                layout="total, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-tab-pane>
        <!-- 上传图片tab栏 -->
        <el-tab-pane label="上传图片" name="upload">
          <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template v-slot:footer>
        <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="sureBtn">确 定</el-button>
        </span>
    </template>
    <!-- 对话框结束 -->
    </el-dialog>
  </div>
</template>

<script>
import { reqPictures } from '@/api/pictures'
import { getToken } from '@/utils/storage'
import defaultImage from '@/assets/default.png'
export default {
  name: 'HmCover',
  props: ['value'],
  data () {
    return {
      pictures: [],
      page: 1,
      per_page: 8,
      collect: false,
      total: 0,
      dialogVisible: false,
      // tab栏切换值
      activeName: 'image',
      // 收集素材库被选中的图片
      selectedImageUrl: null,
      // 图片上传成功面板显示的图片
      imageUrl: '',
      // 当前选中或上传的图片
      currentImage: this.value || defaultImage,
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  // 监听value值的变化
  watch: {
    value () {
      this.currentImage = this.value || defaultImage
    }
  },
  methods: {
    // 点击图片按钮控制模态框的现实与隐藏
    openDialog () {
      this.dialogVisible = true
      this.getPictures()
    },
    // 获取图片素材
    async getPictures () {
      const res = await reqPictures({
        page: this.page,
        per_page: this.per_page,
        collect: this.collect
      })
      this.pictures = res.data.data.results
      this.total = res.data.data.total_count
    },
    handleCurrentChange (val) {
      this.page = val
      this.getPictures()
    },
    // 全部和收藏按钮切换时触发的事件
    btnChange () {
      this.page = 1
      this.getPictures()
    },
    select (imgUrl) {
      this.selectedImageUrl = imgUrl
      console.log(imgUrl)
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = res.data.url
      this.$message.success('上传成功')
    },
    handleError () {
      this.$message.error('服务器繁忙，稍后重试')
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 选好图片,确认按钮
    sureBtn () {
      if (this.activeName === 'image') {
        if (!this.selectedImageUrl) {
          return this.$message.error('请选择一张图片')
        } else {
          this.currentImage = this.selectedImageUrl
        }
      } else if (this.activeName === 'upload') {
        if (!this.imageUrl) {
          return this.$message.error('请上传图片')
        } else {
          this.currentImage = this.imageUrl
        }
      }

      this.$emit('input', this.currentImage)
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped lang='less'>
// 图片按钮
.btn_img {
  width: 150px;
  height: 150px;
  border: 1px dashed #ddd;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
}
/deep/.el-dialog {
 .el-dialog__body {
    padding: 10px 20px;
  }
}
.selected {
  position: relative;
  &::after {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.3) url(~@/assets/selected.png) no-repeat center / 50px 50px;
  }
}
</style>
